package com.common.widget;

import android.content.Context;
import android.text.Selection;
import android.text.Spanned;
import android.util.AttributeSet;
import android.view.ViewDebug.ExportedProperty;
import android.widget.EditText;

import com.common.android.utils.smiley.Smiley;
import com.common.android.utils.smiley.Smileyhelper;

/**
 * 保证输入框在Emoji表情输入时，光标位置的正确性
 * 
 * <br>
 * Created 2014-5-27 下午1:34:42
 * 
 * @version
 * @author HuangYK
 * 
 * @see
 */
public class EmojiEditText extends EditText {

	private int mSelectionStar = 0;

	/**
	 * 
	 * Creates a new instance of EmojiEditText.
	 * <br>Created 2014-6-9 下午5:44:27
	 * @param context 上下文
	 * @param attrs 属性集
	 */
	public EmojiEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	@ExportedProperty(category = "text")
	public int getSelectionStart() {
		CharSequence content = getText();
		if (content instanceof Spanned) {
			mSelectionStar = ((Spanned) content)
					.getSpanStart(Selection.SELECTION_START);
			if (mSelectionStar + 1 == content.length()) {
				String string = content.toString();
				if (string.length() >= 2) {
					// 判断当前光标如果是在有效范围内
					if (mSelectionStar > 0 && mSelectionStar < string.length()) {
						String strTemp = string.substring(mSelectionStar - 1,
								mSelectionStar + 1);
						String emoji = Smileyhelper.getInstance().seekEmoji(
								strTemp, Smiley.TYPE_WEIBO);
						// 如果当前光标处于Emoji特殊字符串的中间，则移到前面，保证进行其他操作不会导致字符串错误
						if (!strTemp.equals(emoji)) {
							mSelectionStar--;
						}
					}
					return mSelectionStar;
				}
			}
			return mSelectionStar;
		} else {
			return -1;
		}
	}

	@Override
	@ExportedProperty(category = "text")
	public int getSelectionEnd() {
		CharSequence content = getText();
		int selectionEnd = 0;
		if (content instanceof Spanned) {
			selectionEnd = ((Spanned) content)
					.getSpanEnd(Selection.SELECTION_END);
			if (selectionEnd < mSelectionStar) {
				selectionEnd = mSelectionStar + 1;
			}
			String string = content.toString();
			if (string.length() >= 2) {
				if (selectionEnd > 0 && selectionEnd < string.length()) {
					String strTemp = string.substring(selectionEnd - 1,
							selectionEnd + 1);
					String emoji = Smileyhelper.getInstance().seekEmoji(
							strTemp, Smiley.TYPE_WEIBO);
					// 如果当前光标处于Emoji特殊字符串的中间，则移到后面，保证进行其他操作不会导致字符串错误
					if (!strTemp.equals(emoji)) {
						selectionEnd++;
					}
				}
			}
			// 限制不大于字符串长度
			if (selectionEnd > content.length()) {
				selectionEnd = content.length();
			}
			return selectionEnd;
		} else {
			return -1;
		}
	}
}
